import { ref, SetupContext } from "vue";
import { SelectDataItem } from "./select.type";
import { UPDATE_MODEL_EVENT } from "../../utils/constants";
export default function (ctx: SetupContext) {
  const selectedItems = ref<SelectDataItem[]>([]);
  return {
    ref: selectedItems,
    add(item: SelectDataItem) {
      const items = selectedItems.value;
      const values = [];
      for (let i = 0, len = items.length; i < len; i++) {
        if (items[i].value === item.value) {
          //已存在
          return i;
        }
        values.push(items[i].value);
      }
      item.selected = true;
      items.push(item);
      values.push(item.value);
      ctx.emit(UPDATE_MODEL_EVENT, values);
      return true;
    },
    remove(item: SelectDataItem) {
      const items = selectedItems.value;
      const values = [];
      let removeIndex = -1;
      for (let i = 0, len = items.length; i < len; i++) {
        if (items[i].value === item.value) {
          removeIndex = i;
          items[i].selected = false;
        } else {
          values.push(items[i].value);
        }
      }
      if (removeIndex !== -1) {
        items.splice(removeIndex, 1);
        ctx.emit(UPDATE_MODEL_EVENT, values);
        return removeIndex;
      }
      return false;
    },
    clear(isEmit?: boolean) {
      selectedItems.value.forEach((item) => {
        item.selected = false;
      });
      selectedItems.value = [];
      isEmit && ctx.emit(UPDATE_MODEL_EVENT, []);
    },
    exist(target: SelectDataItem | string | number): boolean | number {
      let result: boolean | number = false;
      selectedItems.value.forEach((item, i) => {
        if (typeof target === "object") {
          if (target === item) {
            result = i;
            return false;
          }
        } else if (item.value === target) {
          result = i;
          return false;
        }
      });
      return result;
    },
    set(data: SelectDataItem[]) {
      this.clear();
      data.forEach((item) => {
        item.selected = true;
      });
      selectedItems.value = data;
    },
    updateItem(i: number, item: SelectDataItem) {
      selectedItems.value[i] = item;
    },
  };
}
